<template>
<div>
<!--  面包屑区域-->
  <el-breadcrumb separator-class="el-icon-arrow-right">
    <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item>商品管理</el-breadcrumb-item>
    <el-breadcrumb-item>商品参数</el-breadcrumb-item>
  </el-breadcrumb>
<!--  card 卡片区域-->
  <el-card>
<!--    头部警告区域-->
    <el-alert
        title="注意：只允许为第三级分类设置相关参数！"
        type="warning"
        :closable="false"
        show-icon
        >
    </el-alert>
<!--    选择商品区域-->
    <el-row>
      <el-col >
<!--        只允许选中第三极分类-->
        <span>请选择商品分类：</span>
        <el-cascader
            v-model="selectedKeys"
            :options="parentCateList"
            :props="{ expandTrigger: 'hover' , value: 'cat_id',label: 'cat_name',children: 'children' }"
            @change="handleChange"
            clearable
        ></el-cascader>
      </el-col>
    </el-row>
<!--    标签页-->
    <el-tabs v-model="activeName"  @tab-click="handleClick">
      <el-tab-pane label="动态参数" name="many">
<!--        添加参数按钮-->
        <el-row>
          <el-col>
            <el-button type="primary" :disabled="isBtnDisabled" @click="showAddDialog">添加参数</el-button>
          </el-col>
        </el-row>
<!--        动态参数的表格区域-->
        <el-table
            :data="manyAttrList"
        border>
          <el-table-column type="expand">
            <template slot-scope="scope">
              <el-tag v-for="(item,i) in scope.row.attr_vals" :key="i" closable @close="handleClose(i,scope.row)">{{item}}</el-tag>
              <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
              >
              </el-input>
              <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>

            </template>
          </el-table-column>
          <el-table-column type="index"></el-table-column>
          <el-table-column
              prop="attr_name"
              label="参数名称"
              width="500px"
          align="center">
          </el-table-column>
          <el-table-column
              label="操作"
              width="400px"
          align="center">
            <template slot-scope="scope">
              <el-button class="el-icon-edit" type="primary" size="mini" @click="showEditDialog(scope.row)">编辑</el-button>
            <el-button class="el-icon-delete" type="primary"  size="mini" @click="deleteParams(scope.row.attr_id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="静态属性" name="only">
        <!--        添加参数按钮-->
        <el-row>
          <el-col>
            <el-button type="primary" :disabled="isBtnDisabled" @click="showAddDialog">添加属性</el-button>
          </el-col>
        </el-row>
        <!--        静态属性的表格区域-->
        <el-table
            :data="onlyAttrList"
            border>
          <el-table-column type="expand">
            <template slot-scope="scope">
              <el-tag v-for="(item,i) in scope.row.attr_vals" :key="i" closable @close="handleClose(i,scope.row)">{{item}}</el-tag>
              <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
              >
              </el-input>
              <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
            </template>
          </el-table-column>
          <el-table-column type="index"></el-table-column>
          <el-table-column
              prop="attr_name"
              label="属性名称"
              width="500px"
              align="center">
          </el-table-column>
          <el-table-column
              label="操作"
              width="400px"
              align="center">
            <template slot-scope="scope">
              <el-button class="el-icon-edit" type="primary" size="mini" @click="showEditDialog(scope.row)">编辑</el-button>
              <el-button class="el-icon-delete" type="primary"  size="mini" @click="deleteParams(scope.row.attr_id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>
  </el-card>
<!--  添加参数或属性对话框-->
  <el-dialog
      :title=" '添加'+showTitle"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed"
     >
<!--    添加字段表单-->
    <el-form ref="addFormRef" :model="addForm" label-width="80px" :rules="addFormRules">
      <el-form-item :label="titileText" prop="attr_name">
        <el-input v-model="addForm.attr_name"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
    <el-button @click="addDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addAttr">确 定</el-button>
  </span>
  </el-dialog>
<!-- 修改或属性对话框 -->
  <el-dialog
      :title=" '修改'+showTitle"
      :visible.sync="editDialogVisible"
      width="50%"
  >
    <!--    修改参数/属性表单-->
    <el-form ref="editFormRef" :model="editForm" label-width="80px" :rules="editFormRules">
      <el-form-item :label="titileText" prop="attr_name">
        <el-input v-model="editForm.attr_name"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
    <el-button @click="editDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="editAttr">确 定</el-button>
  </span>
  </el-dialog>
</div>
</template>

<script>
export default {
  name: "params",
  data(){
    return {
      // 获取到的商品父级分类数据
      parentCateList:[],
      // 级联选择器选中的数据数组对象
      selectedKeys:[],
      // 商品参数列表
      manyAttrList:[],
      onlyAttrList:[],
      // tabs标签页选中的项
      activeName:'many',
      addDialogVisible:false,
      // 添加参数/属性的表单
      addForm:{
        attr_name:'',
      },
      //添加参数或属性表单的验证规则
      addFormRules:{
        attr_name:[
          {required:true,message:'请填写参数名称',trigger:'blur'}
        ]
      },
      // 级联选择器选中的三级分类的id
      id:0,
      //要修改参数的id
      attrId:0,
      // 修改参数或属性对话框显示或隐藏
      editDialogVisible:false,
      // 添加参数/属性的表单
      editForm:{
        attr_name:'',
      },
      //添加参数或属性表单的验证规则
      editFormRules:{
        attr_name:[
          {required:true,message:'请填写参数名称',trigger:'blur'}
        ]
      },
    }
  },
  created() {
    this.getCateList();

  },
  computed:{
    // 选中的不是第三极分类，禁用按钮
    isBtnDisabled(){
      if(this.selectedKeys.length!==3){
        return true
      }
      return false
    },
    // 添加参数或属性对话框的 title
    showTitle(){
      if(this.activeName==='many'){
        return '动态参数'
      }else {
        return '静态属性'
      }
    },
    // 添加。。。。的表单名字
    titileText(){
      if(this.activeName==='many'){
        return '动态参数'
      }else {
        return '静态属性'
      }
    },
  },
  methods:{
    // 获取分类
    async getCateList(){
      const {data:res}=await this.$http.get('categories');
      if(res.meta.status !==200){
        return this.$message.error("获取分类失败")
      }
      // 获取商品分类成功
      this.parentCateList=res.data;

    },
    // 获取商品参数列表
   async getAttrList(){
     if(this.selectedKeys.length!==3){
       this.selectedKeys=[];
       this.manyAttrList=[];
       this.onlyAttrList=[];
       this.id=0;
       return
     }
     // 选中的是第三级商品
    this.id=this.selectedKeys[2];
     const {data:res}=await this.$http.get(`categories/${this.id}/attributes`,{
        params:{
          sel:this.activeName
        }
      })
     if(res.meta.status !==200){
       return this.$message.error("获取动态参数失败")
     }
     // 获取动态参数列表成功
     // 将每一条参数里面的文字说明分割为一个数组
     res.data.forEach(item=>{
       item.attr_vals=item.attr_vals ? item.attr_vals.split(' '):[];
       item.inputVisible=false;
       item.inputValue='';
     })
     if(this.activeName==='many'){
       this.manyAttrList=res.data;
     }else {
       this.onlyAttrList=res.data;
     }
    },
    // 监听级联选择器的handlechange事件
    handleChange(){
      this.getAttrList()
    },
    // 监听tabs标签的切换
    handleClick(){

      this.getAttrList();
    },
    // 展示添加参数/属性对话框
    showAddDialog(){
      this.addDialogVisible=true;
    },
    // 点击确定按钮，添加动态参数或静态属性
    addAttr(){
      // 首先表单要通过预验证
      this.$refs.addFormRef.validate(async valid=>{
        if(!valid){
          return
        }
        // 通过预验证
        const {data:res}=await this.$http.post(`categories/${this.id}/attributes`,{
          attr_name:this.addForm.attr_name,
          attr_sel:this.activeName
        })
        if(res.meta.status !==201){
          return this.$message.error("添加参数失败")
        }
        this.getAttrList();
        this.addDialogVisible=false;
      })
    },
    // 修改参数/ 属性的确定按钮
    editAttr(){
      // 首先判断表单是否通过验证
      this.$refs.editFormRef.validate( async valid=>{
        if(! valid){
          return
        }
        // 通过验证
        const {data:res}=await this.$http.put(`categories/${this.id}/attributes/${this.attrId}`,{
            attr_name:this.editForm.attr_name,
            attr_sel:this.activeName
        })
        if(res.meta.status !==200){
          return this.$message.error("更新失败")
        }
        // 修改成功
        this.getAttrList();
        this.editDialogVisible=false;

      })
    },
    // 展示修改对话框
    showEditDialog(obj){
      this.attrId=obj.attr_id;
      this.searchName();
      this.editDialogVisible=true;
    },
    // 根据id查询信息
  async  searchName(){
      const {data:res}=await this.$http.get(`categories/${this.id}/attributes/${this.attrId}`,{
       params:{
         attr_sel:this.activeName
       }
      })
    if(res.meta.status !==200){
      return this.$message.error("查询失败")
    }
    // 查询成功
    this.editForm.attr_name=res.data.attr_name;

    },
  async deleteParams(attr_id){
    const confirmResult = await this.$confirm(
        '此操作将永久删除该参数, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    ).catch(err => err)

    // 用户取消了删除的操作
    if (confirmResult !== 'confirm') {
      return this.$message.info('已取消删除！')
    }

    // 删除的业务逻辑
    const { data: res } = await this.$http.delete(
        `categories/${this.id}/attributes/${attr_id}`
    )

    if (res.meta.status !== 200) {
      return this.$message.error('删除参数失败！')
    }

    this.$message.success('删除参数成功！')
    this.getAttrList()

    },
    // 添加参数/属性对话框关闭
    addDialogClosed(){
      this.$refs.addFormRef.resetFields();
    },
    //文本框失去焦点或按enter键触发的函数
   async handleInputConfirm(obj){
      if(obj.inputValue.trim().length===0){
        obj.inputValue='';
        obj.inputVisible=false;
        return
      }
      // 用户输入的内容合法
      obj.attr_vals.push(obj.inputValue.trim());
      obj.inputValue='';
      this.saveAttrVals(obj);
      obj.inputVisible=false;
    },
    // 提交参数描述到服务器
   async saveAttrVals(obj){
      // 把数据提交给服务器
      const {data:res}=await this.$http.put(`categories/${this.id}/attributes/${obj.attr_id}`,
          {
            attr_name:obj.attr_name,
            attr_sel:this.activeName,
            attr_vals:obj.attr_vals.join()
          })
      if(res.meta.status !==200){
        return this.$message.error("修改失败")
      }
      // this.$message.success("修改成功")
    },
    //
    showInput(obj){
      obj.inputVisible=true;
      // 让文本框自动获得焦点
      // $nextTick当页面上元素被重新渲染后才会执行回调函数中的代码
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    // 删除标签
    handleClose(num,obj){
        obj.attr_vals.splice(num,1);
        this.saveAttrVals(obj)
    }
  },
}
</script>

<style scoped lang="less">
.el-col{
  margin-top: 10px;
}
.el-tag{
  margin:15px;
}
.input-new-tag{
  width: 100px;
}
</style>